package org.siteanalyser.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;

import org.siteanalyser.domain.Message;
import org.siteanalyser.domain.TwitterShareResponse;
import org.siteanalyser.service.Service;
import org.siteanalyser.service.SystemException;
import org.springframework.beans.factory.annotation.Required;

import com.google.gson.Gson;

public class TwitterSharesServiceImpl implements Service {
    private String baseUrl;

    public void process(final Message message) throws SystemException {
        makeRequest(message);
    }

    private void makeRequest(final Message message) {
        final String siteNameToCheck = message.getRequest().getUrl();
        InputStream input = null;
        Reader reader = null;
        try {
        	input = new URL(baseUrl+siteNameToCheck).openStream();
	        reader = new InputStreamReader(input, "UTF-8");
        	final Gson gson = new Gson();
        	TwitterShareResponse shareData = gson.fromJson(reader, TwitterShareResponse.class);
	        message.getReport().addReportItem("twitter.shares", shareData.getCount());
		} catch (Exception e) {
            throw new SystemException(e.getMessage());
		} finally {
			if(reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// ignore
				}
			}
		}
	}

    @Required
    public void setBaseUrl(final String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String getBaseUrl() {
        return baseUrl;
    }
}
